package com.rykj.energy.database.service.impl;

import com.rykj.butler.sdk.common.ResponseResult;
import com.rykj.energy.common.utils.CollectionUtils;
import com.rykj.energy.database.mapper.OrganizationMapper;
import com.rykj.energy.database.pojo.Organization;
import com.rykj.energy.database.pojo.vo.OrgMemberVo;
import com.rykj.energy.database.pojo.vo.OrganizationVO;
import com.rykj.energy.database.service.IOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("organizationService")
public class OrganizationServiceImpl implements IOrganizationService {

    @Autowired
    private OrganizationMapper orgMapper;

    @Override
    public void createOrg(Organization orgParam) {
        orgParam.setCreateTime(new Date());
        orgMapper.insert(orgParam);
    }

    @Override
    public Organization findByOrgId(Integer id) {
        return orgMapper.selectById(id);
    }

    @Override
    public void updateOrg(Organization orgParam) {
        Organization orgInfo =orgMapper.selectById(orgParam.getId());
        orgInfo.setName(orgParam.getName());
        orgInfo.setParentId(orgParam.getParentId());
        orgInfo.setSeq(orgParam.getSeq());
        orgInfo.setOrgType(orgParam.getOrgType());
        orgInfo.setBatchNumber(orgParam.getBatchNumber());
        orgInfo.setOrgNum(orgParam.getOrgNum());
        orgMapper.updateById(orgInfo);
    }

    @Override
    public void deleteByOrgId(Integer id) {
        orgMapper.deleteById(id);
    }

    @Override
    public List<OrganizationVO> getOrgTree(Integer orgId,String searchName) {
        List<Integer> orgIds=new ArrayList<>();
        orgIds.add(orgId);
        List<OrganizationVO> orgList = orgMapper.listVO(orgIds,searchName);
        if(CollectionUtils.isNotEmpty(orgList)){
            for (OrganizationVO org:orgList) {
                List<OrganizationVO> childs= getOrgTree(org.getId(),searchName);
                org.setChildren(childs);
            }
        }
        return orgList;
    }

    @Override
    public List<Integer> getChildOrgIdsById(Integer orgId) {
        return orgMapper.getChildOrgIdsById(orgId);
    }

    @Override
    public Organization findByOrgNo(String orgNo) {
        Map<String,Object> colMap= new HashMap<>();
        colMap.put("orgNum",orgNo);
        List<Organization> orgs =orgMapper.selectByMap(colMap);
        return CollectionUtils.isNotEmpty(orgs)?orgs.get(0):null;
    }

    @Override
    public  List<OrgMemberVo>  getListByOrgId(String keyWord, Integer orgId) {
        List<Integer> orgIdList = getChildOrgIdsById(orgId);
        orgIdList.add(orgId);
        List<OrgMemberVo> memberVoList = orgMapper.getListByOrgId(keyWord, orgIdList);
        return memberVoList;
    }
}
